<?php

require_once(dirname(__FILE__).'/DB/Member.php');

define('EXPIRE_SEC', 60 * 60); # 60min

class MemberCache {
    public function get_member ($member_id) {
        $db = new DB_Member('slv');
        $expire = date('Y-m-d h:i:s', time() - EXPIRE_SEC);
        $member_info = $db->select_member($member_id, $expire);
        return array_pop($member_info);
    }

    public function set_member ($member_info) {
        $db = new DB_Member('mst');
        $db->insert_member($member_info);
    }

    public function get_optin_friends ($member_id) {
        $db = new DB_Member('slv');
        $expire = date('Y-m-d h:i:s', time() - EXPIRE_SEC);

        $link = $db->select_link_optin($member_id, $expire);
        if (!isset($link)) {
            return array();
        }
        $member_id_list = explode(':', $link);

        $friend_list = $db->select_member($member_id_list, $expire);
        if (count($member_id_list) != count($friend_list)) {
            return array();
        }
        return $friends;
    }

    public function set_optin_friends ($member_id, $friend_list) {
        $db = new DB_Member('mst');

        $id_list = array();
        foreach ($friend_list as $friend) {
            $id_list[] = $friend['id'];
            $db->insert_member($friend);
        }

        $id_list_str = implode(':', $id_list);
        $db->insert_link_optin($member_id, $id_list_str);
    }

    public function get_friends ($member_id) {
        $db = new DB_Member('slv');
        $expire = date('Y-m-d h:i:s', time() - EXPIRE_SEC);

        $link = $db->select_link($member_id, $expire);
        if (!isset($link)) {
            return array();
        }
        $member_id_list = explode(':', $link);

        $friend_list = $db->select_member($member_id_list, $expire);
        if (count($member_id_list) != count($friend_list)) {
            return array();
        }
        return $friend_list;
    }

    public function set_friends ($member_id, $friend_list) {
        $db = new DB_Member('mst');

        $id_list = array();
        foreach ($friend_list as $friend) {
            $id_list[] = $friend['id'];
            $db->insert_member($friend);
        }

        $id_list_str = implode(':', $id_list);
        $db->insert_link($member_id, $id_list_str);
    }
}
